#!/usr/bin/env python
# -*- coding: utf-8 -*-

# learn website 
# http://blog.csdn.net/pipisorry/article/details/41762945

import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse import csc_matrix
from scipy.sparse import coo_matrix
from scipy.sparse import vstack
from scipy.sparse import lil_matrix
import datetime
import random
from scipy.io import mmwrite,mmread,mminfo

A = coo_matrix([[1,2],[3,4]])
print A
print type(A)
A2array = A.toarray()
print A2array
print type(A2array)
A2dense = A.todense()
print A2dense
print type(A2dense)

row  = np.array([0,0,0,0,1,3,1])
col  = np.array([0,0,0,2,1,3,1])
data = np.array([1,1,1,8,1,1,1])

B = coo_matrix((data, (row,col)), shape=(4,4))
print B
print B.todense()


C = csr_matrix([[1, 5], [4, 0], [1, 3]])
print C
print C.todense()
print C.shape

print C.shape[0]
for i in xrange(C.shape[0]):
    print i
    print C[i]
    print type(C[i])
    print C[i].shape
    
#每次读取csr中的一行    
for c in C:
    print(c)
    
    
# 特征哈希：类 FeatureHasher 是一个快速且低内存消耗的向量化方法，使用了 feature hashing 技术，或可称为”hashing trick”。
# 没有像矢量化那样，为计算训练得到的特征建立哈西表，
# 类 FeatureHasher 的实例使用了一个哈希函数来直接确定特征在样本矩阵中的列号。
# 这样在可检查性上增加了速度减少了内存开销。这个类不会记住输入特征的形状，
    
    

# 将稀疏矩阵横向或者纵向合并   
csr = csr_matrix([[1, 5, 5], [4, 0, 6], [1, 3, 7]])
print(csr.todense())
csr2 = csr_matrix([[3, 0, 9]])
print(csr2.todense())
print(vstack([csr, csr2]).todense())


# 稀疏矩阵点积计算
A = csr_matrix([[1, 2, 0], [0, 0, 3]])
print(A.todense())
v = A.T
print(v.todense())
d = A.dot(v)
print(d)


A = lil_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
v = np.array([1, 0, -1])
s = datetime.datetime.now()
for i in range(100000):
    d = A.dot(v)    #这里v是一个ndarray
print(datetime.datetime.now() - s)

# 故推荐用csr计算点积

csr_mat1 = csr_matrix([1, 2, 0])
csr_mat2 = csr_matrix([1, 0, -1])
similar = (csr_mat1.dot(csr_mat2.transpose()))   #这里csr_mat2也是一个csr_matrix
print(type(similar))
print(similar)
print(similar[0, 0])

# scipy稀疏矩阵在文件中的读取（读取和保存稀疏矩阵）
def save_csr_mat(item_item_sparse_mat_filename=r'.\datasets\lastfm-dataset-1K\item_item_csr_mat.mtx'):
    random.seed(10)
    raw_user_item_mat = random.randint(0, 6, (3, 2))
    d = csr_matrix(raw_user_item_mat)
    print(d.todense())
    print(d)
    mmwrite(item_item_sparse_mat_filename, d)
    print("item_item_sparse_mat_file information: ")
    print(mminfo(item_item_sparse_mat_filename))
    k = mmread(item_item_sparse_mat_filename)
    print(k.todense())
